package com.module.base.base.adapter

import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.*
import com.module.base.base.BaseExceptionViewModel
import com.module.base.ext.observe
import com.module.frame.base.BaseFrameViewModel
import java.lang.reflect.ParameterizedType

/**
 * Author: yanxuwen
 * Date: 2023/7/12
 * Desc: 带有ViewModel的 ViewHolder
 * 由于缓存问题，所以不要带有by lazy
 */
abstract class BaseVmViewHolder<T : Any, VM : BaseExceptionViewModel, DB : ViewDataBinding> :
    BaseViewHolder<T, DB>, ViewModelStoreOwner {


    open lateinit var mViewModel: VM

    open lateinit var mViewModelStore: ViewModelStore

    override fun getViewModelStore(): ViewModelStore {
        return mViewModelStore
    }

    /**
     * 泛型 布局
     */
    constructor(parent: ViewGroup) : super(2, parent)

    private fun createViewModel(): VM {
        val mClass =
            (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1] as Class<VM>
        return ViewModelProvider(this).get(mClass)
    }

    override fun setData(t: T) {
        super.setData(t)
        mViewModelStore = ViewModelStore()
        mViewModel = createViewModel()
    }

    @CallSuper
    override fun onViewRecycled() {
        super.onViewRecycled()
        viewModelStore.clear()
    }
}